import React,{forwardRef,useEffect,useImperativeHandle,useState} from 'react';
import {Upload,message} from 'antd';
import {reqDeleteImg} from '../../api';
import {BASE_IMG_URL} from '../../utils/constants';

/**
 * 新增商品上传图片
 * @param props
 * @param ref
 * @param imgs
 * @returns {JSX.Element}
 * @constructor
 */
function UploadPictures(props,ref){
  // 已经上传的文件列表
  const [fileList, setFileList] = useState([
    // {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ]);

  useEffect(function(){
    const {imgs} = props;
    // 如果传入了imgs属性
    if(imgs && imgs.length>0){
      const fileList = imgs.map((img,index) => ({
        uid: -index, // 每个file都有自己唯一的id
        name: img, // 图片文件名
        status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
        url: BASE_IMG_URL + img
      }));
      setFileList(fileList);
    }
  },[]);

  useImperativeHandle(ref,() => ({ // 暴露给父组件的方法
    getImgs: () => {
      return fileList;
    }
  }))

  /**
   * 上传文件改变时的回调
   * @param newFileList
   * @param file
   */
  const onChange = async ({fileList:newFileList,file}) => {
    // 一旦上传成功, 将当前上传的file的信息修正(name, url)
    if(file.status === "done"){
      const result = file.response;  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
      if(result.status === 0){
        message.success('上传图片成功!');
        const {name, url} = result.data;
        newFileList[newFileList.length-1].name = name;
        newFileList[newFileList.length-1].url = url;
      }else{
        message.error('上传图片失败!');
      }
    }else if(file.status === "removed"){
      const result = await reqDeleteImg(file.name);
      if(result.status === 0){
        message.success('删除图片成功!');
      }else{
        message.error('删除图片失败!');
      }
    }
    setFileList(newFileList);
  };

  /**
   * 点击文件链接或预览图标时的回调
   * @param file
   * @returns {Promise<void>}
   */
  const onPreview = async (file) => {
    let src = file.url;
    if(!src){
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  return (
    <Upload
      // 接受上传的文件类型
      accept="image/*"
      // 图片上传的地址
      action="/api/manage/img/upload"
      // 发到后台的文件参数名
      name="image"
      // 上传列表的回显形式 text,picture,picture-card
      listType="picture-card"
      // 已经上传的文件列表
      fileList={fileList}
      // 上传文件改变时的回调 状态有：uploading done error removed
      onChange={onChange}
      // 点击文件链接或预览图标时的回调
      onPreview={onPreview}
    >
      {fileList.length < 5 && '+ Upload'}
    </Upload>
  );
}

UploadPictures = forwardRef(UploadPictures);
export default UploadPictures;